/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.example.quickstart;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * DefaultMQProducer使用最简单的方式发送消息
 */
public class Producer {
    public static void main(String[] args) throws MQClientException, InterruptedException {

        /*
         * 指定发送者的组名
         */
        DefaultMQProducer producer = new DefaultMQProducer("MyProducerGroup");

        /*
         * 指定NameServer地址。
         * 这个地址可以使用set方法，也可以设定环境变量NAMESRV_ADDR，或者System.setpropertiy("rocketmq.namesrv.addr",'')
         */
        producer.setNamesrvAddr("192.168.232.128:9876;192.168.232.129:9876;192.168.232.130:9876");
        /*
         * 启动消息发送者
         */
        producer.start();

        for (int i = 0; i < 1000; i++) {
            try {

                /*
                 * 消息实例，比别的MQ多了一个TAG的概念。官方建议一个应用就用一个TOPIC，而消息类型用TAG来区分
                 */
                Message msg = new Message("TopicTest" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );

                /*
                 * 同步发送消息
                 */
                SendResult sendResult = producer.send(msg);

                System.out.printf("%s%n", sendResult);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        /*
         * Shut down once the producer instance is not longer in use.
         */
        producer.shutdown();
    }
}
